import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttercalcpokers/compontents/rate_select.dart';
import 'package:fluttercalcpokers/compontents/reset_list.dart';
import 'package:fluttercalcpokers/compontents/total_pokers.dart';
import 'package:fluttercalcpokers/odds/bean/card_bean.dart';
import 'package:fluttercalcpokers/odds/bean/player_bean.dart';
import 'package:fluttercalcpokers/odds/bean/texas_bean.dart';
import 'package:fluttercalcpokers/odds/calculate_util.dart';
import 'package:fluttercalcpokers/utils/common.dart';
import 'package:fluttercalcpokers/utils/rate_list.dart';

import '../compontents/acions_list.dart';
import '../compontents/banner_show.dart';
import '../compontents/poker_select.dart';
import '../compontents/public_poker.dart';
import '../compontents/top_actions.dart';
import '../compontents/user_list.dart';

class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  bool showRate = true;
  List rateList = RateList.getAll();
  List<CardBean> totalPokers = CardBean.getAllCards();
  List<Map> faceCardList = [
    {"name": "A", "value": 14},
    {"name": "2", "value": 2},
    {"name": "3", "value": 3},
    {"name": "4", "value": 4},
    {"name": "5", "value": 5},
    {"name": "6", "value": 6},
    {"name": "7", "value": 7},
    {"name": "8", "value": 8},
    {"name": "9", "value": 9},
    {"name": "10", "value": 10},
    {"name": "J", "value": 11},
    {"name": "Q", "value": 12},
    {"name": "K", "value": 13},
  ];
  List<CardBean> cardList = [];

  bool isSelectPublic = false;
  int publicSelectIndex = 0;
  int pokerSelectIndex = 14;
  int userSelectIndex = 0;
  int userPokerSelectIndex = 0;

  List<Map> publicPokerList = [
    {"key": 0, "src": "", "select": false, "suit": 0},
    {"key": 0, "src": "", "select": false, "suit": 0},
    {"key": 0, "src": "", "select": false, "suit": 0},
    {"key": 0, "src": "", "select": false, "suit": 0},
    {"key": 0, "src": "", "select": false, "suit": 0}
  ];

  List<Map> userList = [
    {
      "firstPoker": 0,
      "firstSuit": 0,
      "firstSrc": "",
      "secondPoker": 0,
      "secondSuit": 0,
      "secondSrc": "",
      "winCal": 0,
      "drawCal": 0,
      "isRate": false,
      "RateValue": "",
      "RateList": []
    },
    {
      "firstPoker": 0,
      "firstSuit": 0,
      "firstSrc": "",
      "secondPoker": 0,
      "secondSuit": 0,
      "secondSrc": "",
      "winCal": 0,
      "drawCal": 0,
      "isRate": false,
      "RateValue": "",
      "RateList": []
    }
  ];

  List<PlayerBean> get players => null;

  TexasBean get curBean => null;

  void addUser() {
    if (userList.length >= 10) {
      return;
    }
    setState(() {
      userList.add({
        "firstPoker": 0,
        "firstSuit": 0,
        "firstSrc": "",
        "secondPoker": 0,
        "secondSuit": 0,
        "secondSrc": "",
        "winCal": 0,
        "drawCal": 0,
        "isRate": false,
        "RateValue": "",
        "RateList": []
      });
    });
  }

  void delUser() {
    if (userList.length <= 2) {
      return;
    }
    setState(() {
      userList.removeLast();
    });
  }

  calculateFuture(List<PlayerBean> players, TexasBean curBean) async {
    return await new Future(() {
      CalculateUtils.execute(players, curBean);
    });
  }

  calcPosibility() async {
    List<PlayerBean> playsList = [];
    TexasBean publicer = TexasBean();
    CalculateUtils calculateUtils;
    for (int i = 0; i < userList.length; i++) {
      Map item = userList[i];
      PlayerBean player = PlayerBean();
      if (item["isRate"] == true) {
        for (int i = 0; i < item["RateList"].length; i++) {
          String _str = item["RateList"][i];
          player.handsList.addAll(CardBean.getHandsStr(_str));
        }
      }
      if (item["isRate"] == false) {
        List<CardBean> hands = new List();
        if (item["secondPoker"] == 0) {
          hands.add(new CardBean(item['firstSuit'], item['firstPoker']));
        }
        if (item["secondPoker"] != 0) {
          hands.add(new CardBean(item['secondSuit'], item['secondPoker']));
        }
        player.hands.addAll(hands);
      }
      playsList.add(player);
    }

    for (int i = 0; i < publicPokerList.length; i++) {
      Map item = publicPokerList[i];
      List<CardBean> cards = [];
      if (i < 3) {
        cards.add(new CardBean(item['suit'], item['key']));
      }
      if (i == 3) {
        publicer.turn = new CardBean(item['suit'], item['key']);
      }
      if (i == 4) {
        publicer.river = new CardBean(item['suit'], item['key']);
      }
    }

    await calculateFuture(playsList, publicer);
    print(playsList.toString());
    setState(() {
      for (int i = 0; i < playsList.length; i++) {
        PlayerBean item = playsList[i];
        userList[i]["winCal"] = formartNum(item.winRate * 100, 2);
        userList[i]["drawCal"] = formartNum(item.drawRate * 100, 2);
      }
    });
  }

  void selectPublicIndex(i) {
    setState(() {
      isSelectPublic = true;
      publicSelectIndex = i;
      for (int j = 0; j < publicPokerList.length; j++) {
        publicPokerList[j]["select"] = false;
        if (i == j) {
          publicPokerList[j]["select"] = true;
        }
      }
    });
  }

  void selectUserItem(i) {
    setState(() {
      isSelectPublic = false;
      userSelectIndex = i;
    });
  }

  void selectUserItemPoker(i) {
    userPokerSelectIndex = i;
  }

  void handleSelectRate() {
    setState(() {
      rateList = RateList.getAll();
      showRate = true;
    });
  }

  void handleResetAll() {
    resetUserPoker();
    resetPublicPoker();
  }

  void handleReSet(context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return ResetList(
            resetAll: handleResetAll,
            resetUsers: resetUserPoker,
            resetPublic: resetPublicPoker,
          );
        });
  }

  void handleRandom() {
    setState(() {
      for (int k = 0; k < totalPokers.length; k++) {
        totalPokers[k].select = false;
      }
      for (int i = 0; i < 5; i++) {
        publicPokerList[i] = setRandomPublic();
      }
      for (int i = 0; i < publicPokerList.length; i++) {
        for (int j = publicPokerList.length - 1; j > i; j--) {
          if (publicPokerList[j]["src"] == publicPokerList[i]["src"]) {
            publicPokerList[j] = setRandomPublic();
          }
        }
      }
      for (int i = 0; i < userList.length; i++) {
        userList[i] = setRandomUser();
      }
      for (int i = 0; i < userList.length; i++) {
        for (int j = userList.length - 1; j > i; j--) {
          if (userList[j]["firstSrc"] == userList[i]["firstSrc"]) {
            userList[j] = setRandomUser();
          }
          if (userList[j]["secondSrc"] == userList[i]["secondSrc"]) {
            userList[j] = setRandomUser();
          }
          if (userList[j]["firstSrc"] == userList[i]["secondSrc"]) {
            userList[j] = setRandomUser();
          }
          if (userList[j]["secondSrc"] == userList[i]["firstSrc"]) {
            userList[j] = setRandomUser();
          }
        }
        for (int j = 0; j < publicPokerList.length; j++) {
          if (publicPokerList[j]["src"] == userList[i]["firstSrc"]) {
            publicPokerList[j] = setRandomPublic();
          }
          if (publicPokerList[j]["src"] == userList[i]["secondSrc"]) {
            publicPokerList[j] = setRandomPublic();
          }
          for (int k = 0; k < totalPokers.length; k++) {
            if (publicPokerList[j]["key"] == totalPokers[k].num &&
                publicPokerList[j]["suit"] == totalPokers[k].suit) {
              totalPokers[k].select = true;
              break;
            }
          }
        }
        for (int k = 0; k < totalPokers.length; k++) {
          if (userList[i]["firstPoker"] == totalPokers[k].num &&
              userList[i]["firstSuit"] == totalPokers[k].suit) {
            totalPokers[k].select = true;
          }
          if (userList[i]["secondPoker"] == totalPokers[k].num &&
              userList[i]["secondSuit"] == totalPokers[k].suit) {
            totalPokers[k].select = true;
          }
        }
      }
    });
  }

  void handleClickMenu(context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("Camera"),
                onTap: () async {
                  print("1111111");
                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("Gallery"),
                onTap: () async {
                  print("object");
                },
              ),
            ],
          );
        });
    return;
  }

  void handleClickStatistical() {
    Navigator.of(context).pushNamed("statistical_page");
  }

  void pokerSelectItems(item, index) {
    setState(() {
      item.select = true;
      if (isSelectPublic == true) {
        for (int i = 0; i < publicSelectIndex; i++) {
          if (publicPokerList[i]["key"] == 0) {
            publicSelectIndex = i;
            publicPokerList[i]["select"] = true;
            setPublicPoker(item);
            return;
          }
        }

        setPublicPoker(item);
        return;
      }

      if (userPokerSelectIndex == 0) {
        setUserFirstPoker(item);
        return;
      }
      setUserSecondPoker(item);
    });
  }

  void totalPokersSelectItem(i) {
    setState(() {
      pokerSelectIndex = i;
      initCards(pokerSelectIndex);
    });
  }

  void cleanItem() {
    setState(() {
      if (isSelectPublic == false) {
        if (userPokerSelectIndex == 0) {
          clearFirstPoker();
          return;
        }
        clearSecondPoker();
      }
      if (isSelectPublic == true) {
        if (publicPokerList[publicSelectIndex]["key"] != 0) {
          for (int j = 0; j < totalPokers.length; j++) {
            if (publicPokerList[publicSelectIndex]["key"] ==
                    totalPokers[j].num &&
                publicPokerList[publicSelectIndex]["suit"] ==
                    totalPokers[j].suit) {
              totalPokers[j].select = false;
              break;
            }
          }
          publicPokerList[publicSelectIndex]["key"] = 0;
          publicPokerList[publicSelectIndex]["src"] = "";
          publicPokerList[publicSelectIndex]["suit"] = 0;
        }
        return;
      }
    });
  }

  void initCards(pokerSelectIndex) {
    cardList = [];
    for (int i = 0; i < totalPokers.length; i++) {
      CardBean item = totalPokers[i];
      if (item.num == pokerSelectIndex) {
        cardList.add(item);
      }
    }
  }

  void handleRateSelectDone(list) {
    String _str = "";
    List<String> _list = [];
    for (int i = 0; i < list.length; i++) {
      if (list[i]["select"] == true) {
        _str += list[i]["name"] + ",";
        _list.add(list[i]["name"]);
      }
    }
    if (_list.length <= 1) {
      return setState(() {
        showRate = false;
      });
    }
    setState(() {
      showRate = false;
      userList[userSelectIndex]["isRate"] = true;
      userList[userSelectIndex]["RateValue"] = _str;
      userList[userSelectIndex]["RateList"] = _list;
    });
  }

  @override
  void initState() {
    initCards(pokerSelectIndex);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
    return Stack(
      children: <Widget>[
        SingleChildScrollView(
          child: Column(
            children: <Widget>[
              BannerShow(),
              TopActions(
                  addUser: addUser,
                  delUser: delUser,
                  calcPosibility: calcPosibility),
              Container(
                width: ScreenUtil().setWidth(750),
                height: ScreenUtil().setHeight(750),
                decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage("images/bg.png"), fit: BoxFit.cover),
                ),
                child: Column(
                  children: <Widget>[
                    Container(
                      width: ScreenUtil().setWidth(750),
                      height: ScreenUtil().setHeight(600),
                      child: Row(
                        children: <Widget>[
                          UserList(
                            userList: userList,
                            userSelectIndex: userSelectIndex,
                            userPokerSelectIndex: userPokerSelectIndex,
                            selectUserItem: selectUserItem,
                            selectUserItemPoker: selectUserItemPoker,
                            isSelectPublic: isSelectPublic,
                          ),
                          ActionsList(
                            handleClickMenu: handleClickMenu,
                            handleReSet: handleReSet,
                            handleClickStatistical: handleClickStatistical,
                            handleSelectRate: handleSelectRate,
                            handleRandom: handleRandom,
                          ),
                        ],
                      ),
                    ),
                    PublicPoker(
                        publicPokerList: publicPokerList,
                        selectPublicIndex: selectPublicIndex,
                        isSelectPublic: isSelectPublic,
                        publicSelectIndex: publicSelectIndex),
                  ],
                ),
              ),
              PokerSelect(
                  cardList: cardList,
                  pokerSelectItems: pokerSelectItems,
                  cleanItem: cleanItem),
              TotalPokers(
                totalPokers: faceCardList,
                totalPokersSelectItem: totalPokersSelectItem,
              ),
            ],
          ),
        ),
        RateSelect(
            showRateSelect: showRate,
            rateList: rateList,
            handleDone: handleRateSelectDone,
            userIndex: userSelectIndex),
      ],
    );
  }

  void setUserFirstPoker(item) {
    userList[userSelectIndex]["isRate"] = false;
    int firstPoker = userList[userSelectIndex]["firstPoker"];
    int firstSuit = userList[userSelectIndex]["firstSuit"];
    if (userPokerSelectIndex == 0) {
      if (firstPoker != 0 && firstSuit != 0) {
        for (int i = 0; i < totalPokers.length; i++) {
          if (firstPoker == totalPokers[i].num &&
              firstSuit == totalPokers[i].suit) {
            totalPokers[i].select = false;
            break;
          }
        }
      }
      userList[userSelectIndex]["firstPoker"] = item.num;
      userList[userSelectIndex]["firstSuit"] = item.suit;
      userList[userSelectIndex]["firstSrc"] = item.getValue();
      userPokerSelectIndex = 1;

      return;
    }
  }

  void clearFirstPoker() {
    int firstPoker = userList[userSelectIndex]["firstPoker"];
    int firstSuit = userList[userSelectIndex]["firstSuit"];
    userList[userSelectIndex]["isRate"] = false;
    if (userPokerSelectIndex == 0) {
      if (firstPoker != 0 && firstSuit != 0) {
        for (int i = 0; i < totalPokers.length; i++) {
          if (firstPoker == totalPokers[i].num &&
              firstSuit == totalPokers[i].suit) {
            totalPokers[i].select = false;
            break;
          }
        }
        userList[userSelectIndex]["firstPoker"] = 0;
        userList[userSelectIndex]["firstSrc"] = "";
        userList[userSelectIndex]["firstSuit"] = 0;
        userList[userSelectIndex]["isRate"] = false;
        userList[userSelectIndex]["RateValue"] = "";
        userList[userSelectIndex]["RateList"] = [];
        return;
      }
      return;
    }
  }

  void clearSecondPoker() {
    int secondPoker = userList[userSelectIndex]["secondPoker"];
    int secondSuit = userList[userSelectIndex]["secondSuit"];
    userList[userSelectIndex]["isRate"] = false;
    if (userPokerSelectIndex != 0) {
      if (secondPoker != 0 && secondSuit != 0) {
        for (int i = 0; i < totalPokers.length; i++) {
          if (secondPoker == totalPokers[i].num &&
              secondSuit == totalPokers[i].suit) {
            totalPokers[i].select = false;
            break;
          }
        }
        userList[userSelectIndex]["secondPoker"] = 0;
        userList[userSelectIndex]["secondSrc"] = "";
        userList[userSelectIndex]["secondSuit"] = 0;
        userList[userSelectIndex]["isRate"] = false;
        userList[userSelectIndex]["RateValue"] = "";
        userList[userSelectIndex]["RateList"] = [];
        return;
      }
      return;
    }
  }

  void setUserSecondPoker(item) {
    userList[userSelectIndex]["isRate"] = false;
    if (userList[userSelectIndex]["firstPoker"] == 0) {
      userPokerSelectIndex = 0;
      setUserFirstPoker(item);
      return;
    }
    int secondPoker = userList[userSelectIndex]["secondPoker"];
    int secondSuit = userList[userSelectIndex]["secondSuit"];
    if (secondPoker != 0 && secondSuit != 0) {
      for (int i = 0; i < totalPokers.length; i++) {
        if (secondPoker == totalPokers[i].num &&
            secondSuit == totalPokers[i].suit) {
          totalPokers[i].select = false;
          break;
        }
      }
    }
    userList[userSelectIndex]["secondPoker"] = item.num;
    userList[userSelectIndex]["secondSuit"] = item.suit;
    userList[userSelectIndex]["secondSrc"] = item.getValue();
    userPokerSelectIndex = 0;
    if (userSelectIndex == userList.length - 1) {
      return;
    }
    userSelectIndex++;
  }

  void setPublicPoker(item) {
    if (publicPokerList[publicSelectIndex]["key"] != 0 &&
        publicPokerList[publicSelectIndex]["suit"] != 0) {
      for (int i = 0; i < totalPokers.length; i++) {
        if (publicPokerList[publicSelectIndex]["key"] == totalPokers[i].num &&
            publicPokerList[publicSelectIndex]["suit"] == totalPokers[i].suit) {
          totalPokers[i].select = false;
          break;
        }
      }
    }

    publicPokerList[publicSelectIndex]["src"] = item.getValue();
    publicPokerList[publicSelectIndex]["key"] = item.num;
    publicPokerList[publicSelectIndex]["suit"] = item.suit;
    if (publicSelectIndex <= 3) {
      publicSelectIndex++;
      publicPokerList[publicSelectIndex]["select"] = true;
    }
  }

  void resetUserPoker() {
    setState(() {
      for (int i = 0; i < userList.length; i++) {
        for (int j = 0; j < totalPokers.length; j++) {
          if (userList[i]["firstPoker"] == totalPokers[j].num &&
              userList[i]["firstSuit"] == totalPokers[j].suit) {
            totalPokers[j].select = false;
            break;
          }
        }
        userSelectIndex = 0;
        userList[i] = {
          "firstPoker": 0,
          "firstSuit": 0,
          "firstSrc": "",
          "secondPoker": 0,
          "secondSuit": 0,
          "secondSrc": "",
          "winCal": 0,
          "drawCal": 0,
          "isRate": false,
          "RateValue": "",
          "RateList": []
        };
      }
    });
  }

  Map setRandomUser() {
    var rng = new Random();
    int firstPoker = rng.nextInt(13) + 2;
    int firstSuit = rng.nextInt(4) + 1;
    int secondPoker = rng.nextInt(13) + 2;
    int secondSuit = rng.nextInt(4) + 1;
//    for(int i=0;i<totalPokers.length;i++){
//      if(totalPokers[i].num==firstPoker&&totalPokers[i].suit==firstSuit){
//        if(totalPokers[i].select==true){
//          firstPoker=rng.nextInt(13) + 2;
//        }
//      }
//    }
    Map item = {
      "firstPoker": firstPoker,
      "firstSuit": firstSuit,
      "firstSrc": "",
      "secondPoker": secondPoker,
      "secondSuit": secondSuit,
      "secondSrc": "",
      "winCal": 0,
      "drawCal": 0,
      "isRate": false,
      "RateValue": "",
      "RateList": []
    };
    item["firstSrc"] =
        CardBean.getCardValue(item["firstPoker"], item["firstSuit"]);
    item["secondSrc"] =
        CardBean.getCardValue(item["secondPoker"], item["secondSuit"]);
    if (item["firstSrc"] == item["secondSrc"]) {
      return setRandomUser();
    }
    return item;
  }

  Map setRandomPublic() {
    var rng = new Random();
    Map item = {
      "key": rng.nextInt(13) + 2,
      "src": "",
      "select": false,
      "suit": rng.nextInt(4) + 1
    };
    item["src"] = CardBean.getCardValue(item["key"], item["suit"]);
    return item;
  }

  void resetPublicPoker() {
    setState(() {
      for (int i = 0; i < publicPokerList.length; i++) {
        for (int j = 0; j < totalPokers.length; j++) {
          if (publicPokerList[i]["key"] == totalPokers[j].num &&
              publicPokerList[i]["suit"] == totalPokers[j].suit) {
            totalPokers[j].select = false;
            break;
          }
        }
      }
      publicPokerList = [
        {"key": 0, "src": "", "select": false, "suit": 0},
        {"key": 0, "src": "", "select": false, "suit": 0},
        {"key": 0, "src": "", "select": false, "suit": 0},
        {"key": 0, "src": "", "select": false, "suit": 0},
        {"key": 0, "src": "", "select": false, "suit": 0}
      ];
    });
  }
}
